package com.qf.controller;

import com.qf.entiy.Product;
import com.qf.service.Impl.ProductServiceImpl;
import com.qf.service.ProductService;

import com.qf.util.Constants;
import com.qf.util.Page;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/*
    Dell
    2021/10/9
    11:28
*/
@WebServlet("/product")
public class ProductController extends BaseController {
    public String showAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String pageIndex = request.getParameter("pageIndex");
        if(pageIndex==null){
            pageIndex = "1";
        }
        Page page  = new Page(Integer.valueOf(pageIndex));
        ProductService productService = new ProductServiceImpl();
        List<Product> productList = productService.showAll(page);
        System.out.println(productList);
        request.setAttribute("productList", productList);
        request.setAttribute("page", page);
        return Constants.FORWARD+"/list.jsp";
    }
    public String alter(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String id = request.getParameter("id");
        String name = request.getParameter("name");
        String cid = request.getParameter("cid");
        String deadline = request.getParameter("date");
        String vender = request.getParameter("vender");
        String price = request.getParameter("price");
        String type = request.getParameter("type");
        Date date = null;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        try {
            date = simpleDateFormat.parse(deadline);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        System.out.println(date);
        Product product = new Product(0,name,date, vender, Double.valueOf(price), Integer.valueOf(type), null);
        ProductService productService = new ProductServiceImpl();
        if(id==""){
           productService.add(product, Integer.valueOf(cid));
        }else{
            product.setId(Integer.valueOf(id));
            productService.updateProduct(product, Integer.valueOf(cid));
        }
        return Constants.REDIRECT+"/product?method=showAll";
    }
    public String delete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String id = request.getParameter("id");
        ProductService productService = new ProductServiceImpl();
        Integer delete = productService.delete(Integer.valueOf(id));
        //return Constants.REDIRECT+"/product?method=showAll";
        return delete.toString();
    }
}
